import 'package:enterprise_v6_app/app/core/core.dart';

/// 颜色-类型指示器
class CustomColorTypeIndicator extends StatelessWidget {
  const CustomColorTypeIndicator({
    required this.colors,
    required this.types,
    this.vals,
    this.matrix = (4, 2),
    super.key,
    this.builder,
    this.padding = EdgeInsets.zero,
  }) : assert((colors.length == types.length) && (vals == null || vals.length == colors.length), '数量不一致');

  /// 颜色
  final List<Color> colors;

  /// 类型
  final List<String> types;

  /// 每个类型的值（有多少个）
  final List<String>? vals;

  /// 显示为几行几列
  final (int x, int y) matrix;

  /// 自定义构建
  final Widget Function(String item, String? val, Color color)? builder;

  final EdgeInsetsGeometry padding;

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (_, cons) {
      final width = cons.maxWidth / matrix.$1 - padding.horizontal;
      return Column(
        children: List.generate(
          matrix.$2,
          (y) => Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: List.generate(matrix.$1, (x) => _buildItem(x, y, width)),
          ),
        ),
      );
    });
  }

  Widget _buildItem(int x, int y, double width) {
    if (x + y * matrix.$1 >= colors.length) {
      return const SizedBox();
    }
    final idx = x + y * matrix.$1;
    final color = colors[idx];
    final type = types[idx];
    final val = vals == null ? null : vals![idx];
    final result = builder?.call(type, val, color);
    if (result != null) return result;
    return ConstrainedBox(
      constraints: BoxConstraints(
        maxWidth: width,
      ),
      child: Padding(
        padding: padding,
        child: Row(
          children: [
            Container(
              width: 10.w,
              height: 10.w,
              decoration: BoxDecoration(
                color: color,
                borderRadius: BorderRadius.circular(2.w),
              ),
            ),
            AppGaps.hGap6,
            Text(
              type,
              style: TextStyle(
                fontSize: 12.sp,
                color: const Color(0xFFA0A7B5),
              ),
            ),
            if (vals != null) ...[
              AppGaps.hGap6,
              Text(
                val!,
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Colors.black,
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}
